package com.aisi.backend.filter;

import com.aisi.backend.domain.RestBean;
import com.aisi.backend.domain.RestCode;
import com.alibaba.fastjson2.JSON;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * @Author: shenjianZ
 * @Date: 2024/4/30 下午10:50
 * @Description:
 */


@WebFilter("/*")
public class CorsFilter extends HttpFilter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 设置允许跨域请求的域名
        response.setHeader("Access-Control-Allow-Origin", "*");
        // 设置允许跨域请求的方法
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT,OPTIONS, DELETE, HEAD");
        //
        response.setHeader("Access-Control-Max-Age", "3600");
        // 设置允许跨域请求的请求头
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
        String method = request.getMethod();
        // 如果是跨域预检请求,则直接在此响应 200
        if (method.equalsIgnoreCase("OPTIONS")) {
            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(RestBean.success(RestCode.SUCCESS)));
            return;
        }
        // 非预检请求 ，放行
        filterChain.doFilter(request, response);
    }

}
